package com.chenjiaru.thread.startthread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * 创建线程方式三：实现Callable接口
 */
@Slf4j
public class CallableDemo {
    public static void main(String[] arr) {
        log.info("程序开始...");
        FutureTask<Integer> futureTask = new FutureTask<>(new MyCallable());
        new Thread(futureTask).start();
        try {
            Integer sum = futureTask.get(2, TimeUnit.SECONDS);     // 阻塞等待此线程运行完毕，可以当成闭锁来用
            log.info("sum={}", sum);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("程序结束...");
    }
}

class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        return IntStream.range(1, 1000).sum();
    }
}
